package com.jason.lightreader.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jason.lightreader.entity.Score;
import com.jason.lightreader.mapper.ArticleMapper;
import com.jason.lightreader.mapper.ScoreMapper;
import com.jason.lightreader.service.ScoreService;
import com.jason.lightreader.util.SecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ScoreServiceImpl extends ServiceImpl<ScoreMapper, Score> implements ScoreService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Boolean AddPoints(Integer articleID, Integer score) {
        Integer userID = SecurityContext.getUser().getId();
        LambdaQueryWrapper<Score> wrapper = new LambdaQueryWrapper<>(Score.class)
                .eq(Score::getUserId, userID)
                .eq(Score::getArticleId, articleID);
        //如果记录不存在
        Score record = this.getOne(wrapper);
        if (record == null) {
            //创建一条记录
            return this.save(new Score().setUserId(userID).setArticleId(articleID).setScore(score));
        }
        //在原来基础上+score
        record.setScore(record.getScore() + score);
        return this.update(record, wrapper);
    }

    @Override
    public Boolean DecPoints(Integer articleID, Integer score) {
        Integer userID = SecurityContext.getUser().getId();
        LambdaQueryWrapper<Score> wrapper = new LambdaQueryWrapper<>(Score.class)
                .eq(Score::getUserId, userID)
                .eq(Score::getArticleId, articleID);
        //如果记录不存在
        Score record = this.getOne(wrapper);
        if (record == null) {
            //创建一条记录:因为记录刚创建所以默认0分
            return this.save(new Score().setUserId(userID).setArticleId(articleID));
        }
        //如果分数为0直接不扣分
        if (record.getScore().equals(0)) {
            return false;
        }
        //在原来基础上-score
        int result = record.getScore() - score;
        record.setScore(Math.max(result, 0));
        return this.update(record, wrapper);
    }
}
